<template>
  <!--角色权限（菜单）绑定Modal-->
  <a-modal
    title="角色权限绑定"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleModalOk"
    @cancel="handleModalCancel"
  >
    <div style="max-height: 400px ;padding-left: 50px; overflow: auto">
      <a-tree
        :treeData="treeFmt"
        :defaultExpandAll="true"
        v-model="checkedKeys"
        checkable
      >
        <template slot="titleFmt" slot-scope="text">
          <template v-if="text.icon!==null">
            <a-icon :type="text.icon" style="margin-right: 3px" />
          </template>
          {{ text.title }}
        </template>
      </a-tree>
    </div>
  </a-modal>
</template>
<script>
import api from '../system'
import { treePermissionHasParentIdsConvert } from '@/utils/antUtil'

// 角色权限（菜单）绑定Modal
export default {
  name: 'RoleModalPermissionBinding',
  props: {
    roleId: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      visible: false,
      confirmLoading: false,
      width: 800,
      treeData: [],
      checkedKeys: []
    }
  },
  watch: {
    roleId: {
      handler (newValue, oldValue) {
        this.roleId = newValue
        this.queryCheckedKeys()
      },
      // 深度监听 || 发现对象内部值的变化
      deep: true,
      // 当值第一次绑定的时候，触发执行监听函数
      immediate: true
    }
  },
  computed: {
    treeFmt () {
      let { treeData } = this
      treeData = treeData || []
      const tree = treePermissionHasParentIdsConvert(treeData)
      return tree
    }
  },
  created () {
    this.queryMenuTree()
  },
  methods: {
    // Modal show
    showModal (param = {}) {
      this.visible = true
    },
    // Modal hide
    hideModal () {
      this.visible = false
    },
    // Modal 确定按钮--保存
    handleModalOk () {
      const param = { roleId: this.roleId, checkedKeys: this.checkedKeys }
      this.axios.post(api.role.updateSysRolePermission, param)
        .then((response) => {
          if (response.code === 200) {
            this.$message.success('绑定成功')
            this.hideModal()
          } else {
            this.$message.error('绑定失败：' + response.message)
          }
        })
        .catch((error) => {
          this.$message.error('绑定异常：' + error)
        })
    },
    // Modal 取消按钮
    handleModalCancel () {
      this.hideModal()
    },
    // 查询角色拥有的keys
    queryCheckedKeys () {
      const roleId = this.roleId || undefined
      if (roleId) {
        this.axios.get(api.permission.getAntCheckedKeysByRoleId + '/' + roleId)
          .then((res) => {
            this.checkedKeys = res.data || []
          })
          .catch((error) => {
            console.log('请求异常...', error)
          })
      }
    },
    // 查询菜单权限tree
    queryMenuTree () {
      this.axios.post(api.permission.getAllMenuTree)
        .then((res) => {
          this.treeData = res.data
        })
        .catch((error) => {
          console.log('请求异常...', error)
        })
    }
  }
}
</script>
